#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>

int tickets=1000;
pthread_mutex_t lock;

void* Routine(void* arg)
{
  const char* name=(char*)arg;

  while(1)
  {
    pthread_mutex_lock(&lock);
    if(tickets>0)
    {
      usleep(10000);
      printf("[%s] get a tiket: %d\n",name,tickets--);
      pthread_mutex_unlock(&lock);
    }
    else 
    {
      pthread_mutex_unlock(&lock);
      break;
    }
  }
  printf("%s quit!\n",name);
  return (void*)0;
}

int main()
{
 pthread_t t1,t2,t3,t4;
 pthread_mutex_init(&lock,NULL);//锁的初始化

 pthread_create (&t1,NULL,Routine,"thread 1");//第二个参数设置线程属性，一般默认
 pthread_create(&t2,NULL,Routine,"thread 2");//第二个参数设置线程属性，一般默认
 pthread_create(&t3,NULL,Routine,"thread 3");//第二个参数设置线程属性，一般默认
 pthread_create(&t4,NULL,Routine,"thread 4");//第二个参数设置线程属性，一般默认

 pthread_join(t1,NULL);
 pthread_join(t2,NULL);
 pthread_join(t3,NULL);
 pthread_join(t4,NULL);
 pthread_mutex_destroy(&lock);//锁的释放
 
  return 0;
}
